from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.views import View

from carapp.cartmanager import getCartManger


# Create your views here.
class AddCartView(View):
    def post(self,request):
        #在多级字典数据的时候，需要手动设置modified=True,实时的将数据存入到session对象中
        request.session.modified = True

        #1.获取当前操作类型

        flag = request.POST.get('flag','')

        #2.判断当前操作类型
        if flag == 'add':
            #创建Cartmanager对象
            cartManagerObj = getCartManger(request)
            #加入购物车操作
            cartManagerObj.add(**request.POST.dict())

        elif flag == 'plus':
            # 创建Cartmanager对象
            cartManagerObj = getCartManger(request)
            #修改商品数量(添加操作)
            cartManagerObj.update(step=1,**request.POST.dict())

        elif flag == 'minus':
            # 创建Cartmanager对象
            cartManagerObj = getCartManger(request)
            # 修改商品数量(减少操作)
            cartManagerObj.update(step=-1, **request.POST.dict())

        elif flag == 'delete':
            # 创建Cartmanager对象
            cartManagerObj = getCartManger(request)
            # 逻辑删除购物车选项
            cartManagerObj.delete(**request.POST.dict())


        return HttpResponseRedirect('/cart/queryAll/')


class CartListView(View):
    def get(self,request):
        #创建cartManager对象
        cartManagerObj = getCartManger(request)

        #查询所有购物项信息
        cartList = cartManagerObj.queryAll()


        return render(request,'cart.html',{'cartList':cartList})